
package com.monlyu.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.monlyu.config.AppArgs;
import com.monlyu.model.TmpUser;
import com.monlyu.vo.User;

/**
 * @author monlyu
 * @since 2009-12-15
 */
public class WebOptUtil {

    // 系统属性
    public static Map<String, String> ALL_SYSTEM_PROPERY = new HashMap<String, String>();

    /** 装用户session的名称 */
    public final static String CUR_USER = "curUser";
    public final static String TMP_USER = "TmpUser";

    public static final AppArgs APP_ARGS = new AppArgs();

    /** 新建一个本地线程.用于传输数据 */
    private static ThreadLocal<Object> localThread = new ThreadLocal<Object>();

    /**
     * 用户进入session时候的登记
     * 
     * @param user
     */
    public static void remember(final User user){
        final HttpServletRequest request = ServletActionContext.getRequest();
        request.getSession().setAttribute(CUR_USER, user);
    }

    // 记住最原始的信息
    public static void rememberTmpUser(TmpUser tmpUser){
        final HttpServletRequest request = ServletActionContext.getRequest();
        request.getSession().setAttribute(TMP_USER, tmpUser);
    }

    /**
     * 获得配置文件
     */
    public static String getConfig(String key){
        return ALL_SYSTEM_PROPERY.get(key);
    }

    /**
     * 把数据添加到本地线程中去
     * 
     * @since 2010-1-14
     */
    public static void addData2Thread(Object data){
        localThread.set(null);
        localThread.set(data);
    }

    public static String getDataInLoaclThread(){
        return StringUtil.trim(localThread.get());
    }

    /**
     * 用户点击退出.Session失效
     */
    public static void userExit(){
        final HttpServletRequest request = ServletActionContext.getRequest();
        request.getSession().removeAttribute(CUR_USER);
        request.getSession().invalidate();
    }

    /**
     * 获取当前用户
     * 
     * @return 当前用户
     */
    public static User curUser(){
        final HttpServletRequest request = ServletActionContext.getRequest();
        return curUser(request);
    }

    /**
     * 方法从载,从页面获取用户是否登录
     * 
     * @param request
     * @return 当前用户
     */
    public static User curUser(HttpServletRequest request){
        if (request == null) {
            return null;
        }
        return (User) request.getSession().getAttribute(CUR_USER);
    }

    /**
     * 用户是否登录
     * 
     * @return 判断是否登录
     */
    public static boolean hasLogon(){
        return curUser() != null;
    }
}
